package com.ra.landlord;

import java.io.File;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Date;
import java.util.List;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.DiscriminatorColumn;
import javax.persistence.DiscriminatorType;
import javax.persistence.DiscriminatorValue;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;
import javax.persistence.Transient;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.annotations.Index;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import org.hibernate.annotations.Where;

import com.googlecode.cswish.annotation.cm;
import com.ra.system.Version;
import com.ra.util.DateTimeUtil;

/**
 * 合约
 * 
 * @author Jerry.Feng Date: 2014-07-30
 */
@Entity
@Table(name = "ra_agreement")
@Inheritance(strategy = InheritanceType.SINGLE_TABLE)
@DiscriminatorColumn(name = "agreement_state", discriminatorType = DiscriminatorType.INTEGER)
@DiscriminatorValue("2")
@Where(clause = "agreement_state != 2")
public class Agreement implements Version, LandlordOwner {

	@cm("出租周期单位：月")
	public static final Integer TENANCY_TYPE_MONTH = 0;
	@cm("出租周期单位：年")
	public static final Integer TENANCY_TYPE_YEAR = 1;
	
	// 收费周期: 月
	public final static Integer RENT_CYCLE_TYPE_MONTH = 0;
	// 收费周期: 年
	public final static Integer RENT_CYCLE_TYPE_YEAR = 1;
	
	@cm("有效")
	public final static Integer AGREEMENT_STATE_VALID = 0;
	
	@cm("无效")
	public final static Integer AGREEMENT_STATE_INVALID = 1;
	
	@cm("存根合同，不计算任何费用")
	public final static Integer AGREEMENT_STATE_STUB = 2;

	private Integer id;
	
	// 房间
	private Room room;
	
	// 承租人
	private TenantUser tenantUser;
	
	// 网络IP
	private String netIp;
	
	// 押金
	private String deposit;
	
	// 租金
	private BigDecimal rentPay;
	
	// 订金
	private String bookPay;
	
	// 租期
	private String rentPeriod;
	
	// 起租日期
	private String rentBeginDate;
	
	// 到期日期
	private String rentEndDate;
	
	// 退房时间
	private String rentLeaveDate;
	
	// 退回费用
	private String returnFee;
	//押付模式（0:一押一付；1:两押一付；2：三押一付；3：四押一付；）
	private Integer rentType;
	
	// 收费周期类型：月；年
	private Integer rentCycleType;
	
	// 收费周期：一个月；半年；一年
	// 从0开始, 0-11表示1,2,3个月等等
	private Integer rentCycle;
	//出租方式（0：自然月；1：租赁月）
	// 出租方式: 0,自然月；1,租赁月
	private Integer rentMode;
	
	// 自然月开始结束时间
	private String modeDt;
	
	// 合约有效, 只读属性, 其修改由DiscriminatorColumn决定
	private Integer agreementState;
	
	// 换房信息
	private String changeInfo;
	
	// 备注
	private String remark;
	
	// 经办人
	private LandlordUser agent;
	//费用增长类型（0表示不使用）
	// 费用增长类型
	private Integer rentGrowthType;
	
	// 费用增长的金额
	private String rentGrowthMoney;
	
	private LandlordOwnerUser landlordUser;
	
	// (冗余字段，数据对应Fee的balance)余额， 为正表示有存， 负表示还有欠缴
	private BigDecimal balance;
	
	//合约下的费用
	private List<Fee> fees;
	
	private Integer version;
	
	private Integer status;
	
	@cm("付款方式  押几")
	private Integer depositNum;
	
	@cm("付款方式  付几") //交租日期=起租日期+付几月  -提前多天
	private Integer payNum;
	
	@cm("提前多少天 付款")
	private Integer advanceNum;
	
	@cm("租期")
	private Integer tenancy;
	
	@cm("租期类型：月、年")
	private Integer tenancyType;
	
	//transient
	private File photo;
	
	@cm("合约时间")
	private String photoFileName;
	
	//@Transient 其他费用总额
	private BigDecimal fixedFeeTotalAmount;
	
	//@Transient
	private FeeRecord lastFeeRecord;

	@Id
	@GeneratedValue
	@Column(name = "agreement_id")
	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}
	
	//--
	
	@Transient
	public void adaptRentPeriod()
	{
		if (StringUtils.isNotEmpty(this.rentPeriod))
		{
			if (StringUtils.isNumeric(this.rentPeriod))
			{
				this.tenancy = Integer.valueOf(this.rentPeriod);
				this.tenancyType = TENANCY_TYPE_MONTH;
			}
			else
			{
				this.tenancy = 6;
				this.tenancyType = TENANCY_TYPE_MONTH;
			}
		}
	}
	
	@Transient
	public void adaptRentPeriodNew()
	{
		if (this.tenancy != null)
		{
			int rentCycleMonth = (TENANCY_TYPE_YEAR.equals(this.tenancyType)) ? this.tenancy * 12 : this.tenancy;
			this.rentPeriod = String.valueOf(rentCycleMonth);
			this.rentCycleType = RENT_CYCLE_TYPE_MONTH;
		}
	}

	/**
	 * 兼容新字段: 压付模式 (老适配新)
	 */
	@Transient
	public void adaptRentType()
	{
		if (this.rentType == null)
		{
			return;
		}
		
		switch (this.rentType) 
		{
		case 0:
			adaptRentTypeSet(1, 1);
			break;
		case 1:
			adaptRentTypeSet(2, 1);
			break;
		case 2:
			adaptRentTypeSet(3, 1);
			break;
		case 3:
			adaptRentTypeSet(4, 1);
			break;
		case 4:
			adaptRentTypeSet(1, 2);
			break;
		case 5:
			adaptRentTypeSet(2, 2);
			break;
		case 6:
			adaptRentTypeSet(3, 2);
			break;
		case 7:
			adaptRentTypeSet(4, 2);
			break;
		case 8:
			adaptRentTypeSet(1, 3);
			break;
		case 9:
			adaptRentTypeSet(2, 3);
			break;
		case 10:
			adaptRentTypeSet(3, 3);
			break;
		case 11:
			adaptRentTypeSet(4, 3);
			break;

		default:
			adaptRentTypeSet(1, 1);
			break;
		}
	}
	
	/**
	 * 兼容老字段: 压付模式(新适配老)
	 */
	@Transient
	public void adaptRentTypeNew()
	{
		if (this.depositNum == null)
		{
			return;
		}
		
		int pay = this.payNum;
		switch (this.depositNum) 
		{
		case 1:
			if (pay == 1)
			{
				setRentType(0);
			}
			else if (pay == 2)
			{
				setRentType(4);
			}
			else if (pay == 3)
			{
				setRentType(8);
			}
			else
			{
				setRentType(8);
			}
			
			break;
		case 2:
			if (pay == 1)
			{
				setRentType(1);
			}
			else if (pay == 2)
			{
				setRentType(5);
			}
			else if (pay == 3)
			{
				setRentType(9);
			}
			else
			{
				setRentType(9);
			}
			break;
		case 3:
			if (pay == 1)
			{
				setRentType(2);
			}
			else if (pay == 2)
			{
				setRentType(6);
			}
			else if (pay == 3)
			{
				setRentType(10);
			}
			else
			{
				setRentType(10);
			}
			break;
		case 4:
			if (pay == 1)
			{
				setRentType(3);
			}
			else if (pay == 2)
			{
				setRentType(7);
			}
			else if (pay == 3)
			{
				setRentType(11);
			}
			else
			{
				setRentType(11);
			}
			break;

		default:
			setRentType(0);
			break;
		}
	}
	
	private void adaptRentTypeSet(int deposit, int pay)
	{
		this.depositNum = deposit;
		this.payNum = pay;
	}
	
	//--
	
	@Column(name = "net_ip")
	public String getNetIp() {
		return netIp;
	}

	public void setNetIp(String netIp) {
		this.netIp = netIp;
	}

	@Column(name = "deposit")
	public String getDeposit() {
		return deposit;
	}

	public void setDeposit(String deposit) {
		this.deposit = deposit;
	}

	@Column(name = "rent_pay")
	public BigDecimal getRentPay() {
		return rentPay;
	}

	public void setRentPay(BigDecimal rentPay) {
		this.rentPay = rentPay;
	}

	@Column(name = "book_pay")
	public String getBookPay() {
		return bookPay;
	}

	public void setBookPay(String bookPay) {
		this.bookPay = bookPay;
	}

	@Column(name = "rent_period")
	public String getRentPeriod() {
		return rentPeriod;
	}

	public void setRentPeriod(String rentPeriod) {
		this.rentPeriod = rentPeriod;
	}

	@Column(name = "rent_begin_date")
	public String getRentBeginDate() {
		return rentBeginDate;
	}

	public void setRentBeginDate(String rentBeginDate) {
		this.rentBeginDate = rentBeginDate;
	}

	@Column(name = "rent_end_date")
	public String getRentEndDate() {
		return rentEndDate;
	}

	public void setRentEndDate(String rentEndDate) {
		this.rentEndDate = rentEndDate;
	}

	@Column(name = "rent_leave_date")
	public String getRentLeaveDate() {
		return rentLeaveDate;
	}

	public void setRentLeaveDate(String rentLeaveDate) {
		this.rentLeaveDate = rentLeaveDate;
	}

	@Column(name = "return_fee")
	public String getReturnFee() {
		return returnFee;
	}

	public void setReturnFee(String returnFee) {
		this.returnFee = returnFee;
	}

	@Column(name = "rent_type")
	public Integer getRentType() {
		return rentType;
	}

	public void setRentType(Integer rentType) {
		this.rentType = rentType;
	}

	@Column(name = "rent_cycle_type")
	public Integer getRentCycleType() {
		return rentCycleType;
	}

	public void setRentCycleType(Integer rentCycleType) {
		this.rentCycleType = rentCycleType;
	}

	@Column(name = "rent_cycle")
	public Integer getRentCycle() {
		return rentCycle;
	}

	public void setRentCycle(Integer rentCycle) {
		this.rentCycle = rentCycle;
	}

	@Column(name = "rent_mode")
	public Integer getRentMode() {
		return rentMode;
	}

	public void setRentMode(Integer rentMode) {
		this.rentMode = rentMode;
	}

	@Column(name = "mode_dt")
	public String getModeDt() {
		return modeDt;
	}

	public void setModeDt(String modeDt) {
		this.modeDt = modeDt;
	}

	@Column(name = "agreement_state", insertable=false, updatable=false)
	@Index(name="idx_ra_agreement_rs",columnNames={"room_id","agreement_state"})
	public Integer getAgreementState() {
		return agreementState;
	}

	public void setAgreementState(Integer agreementState) {
		this.agreementState = agreementState;
	}
	
	@Column(name = "change_info")
	public String getChangeInfo() {
		return changeInfo;
	}

	public void setChangeInfo(String changeInfo) {
		this.changeInfo = changeInfo;
	}

	@Column(name = "remark")
	public String getRemark() {
		return remark;
	}

	public void setRemark(String remark) {
		this.remark = remark;
	}
	
	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name = "admin_id")
	public LandlordUser getAgent() {
		return agent;
	}

	public void setAgent(LandlordUser agent) {
		this.agent = agent;
	}
	

	@Column(name = "rent_growth_type")
	public Integer getRentGrowthType() {
		return rentGrowthType;
	}

	public void setRentGrowthType(Integer rentGrowthType) {
		this.rentGrowthType = rentGrowthType;
	}

	@Column(name = "rent_growth_money")
	public String getRentGrowthMoney() {
		return rentGrowthMoney;
	}

	public void setRentGrowthMoney(String rentGrowthMoney) {
		this.rentGrowthMoney = rentGrowthMoney;
	}

	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name = "room_id")
	@Index(name="idx_ra_agreement_room_id")
	@NotFound(action=NotFoundAction.IGNORE)
	public Room getRoom() {
		return room;
	}

	public void setRoom(Room room) {
		this.room = room;
	}
	
	@ManyToOne(targetEntity=TenantUser.class, fetch=FetchType.LAZY, cascade = {CascadeType.PERSIST, CascadeType.MERGE})
	@JoinColumn(name = "user_id")
	public TenantUser getTenantUser() {
		return tenantUser;
	}

	public void setTenantUser(TenantUser tenantUser) {
		this.tenantUser = tenantUser;
	}

	@ManyToOne(fetch=FetchType.LAZY)
	@JoinColumn(name = "createuserid")
	public LandlordOwnerUser getLandlordUser() {
		return landlordUser;
	}

	public void setLandlordUser(LandlordOwnerUser landlordUser) {
		this.landlordUser = landlordUser;
	}
	
	@Column(name = "version_id")
	public Integer getVersion() {
		return version;
	}

	public void setVersion(Integer version) {
		this.version = version;
	}
	
	@Column(name = "data_status")
	public Integer getStatus() {
		return status;
	}

	public void setStatus(Integer status) {
		this.status = status;
	}
	
	@OneToMany(targetEntity=Fee.class, mappedBy="agreement", fetch=FetchType.LAZY,
			cascade = {CascadeType.ALL}, orphanRemoval=true)
	@Where(clause = "data_status=1 or data_status=2")
	@OrderBy("id desc")
	/*@IndexColumn(name="feeIndexCol")*/
	public List<Fee> getFees() {
		return fees;
	}

	public void setFees(List<Fee> fees) {
		this.fees = fees;
	}
	
	@Transient
	public BigDecimal getBalance() {
		return balance;
	}

	public void setBalance(BigDecimal balance) {
		this.balance = balance;
	}
	
	@Transient
	public String getRentBeginDateDesc() {
		if (rentBeginDate != null && rentBeginDate.length() > 9) {
			return rentBeginDate.substring(0, 10);
		}
		return rentBeginDate;
	}
	
	@Transient
	public String getRentEndDateDesc() {
		if (rentEndDate != null && rentEndDate.length() > 9) {
			return rentEndDate.substring(0, 10);
		}
		return rentEndDate;
	}
	
	@Transient
	public String getRentLeaveDateDesc() {
		if (rentLeaveDate != null && rentLeaveDate.length() > 9) {
			return rentLeaveDate.substring(0, 10);
		}
		return rentLeaveDate;
	}
	
	@Transient
	public Integer getExpire() {
		
		Date rentEndDate = DateTimeUtil.StrToDate(getRentEndDate(),DateTimeUtil.DATETIME_FORMAT);
		if (rentEndDate != null && rentEndDate.after(new Date())) {
			return 1;
		}
		return 0;
	}

	public Integer getDepositNum() {
		return depositNum;
	}

	public void setDepositNum(Integer depositNum) {
		this.depositNum = depositNum;
	}

	public Integer getPayNum() {
		return payNum;
	}

	public void setPayNum(Integer payNum) {
		this.payNum = payNum;
	}

	@Column(columnDefinition = "int(11) default 3")
	public Integer getAdvanceNum() {
		return advanceNum;
	}

	public void setAdvanceNum(Integer advanceNum) {
		this.advanceNum = advanceNum;
	}

	@Transient
	public File getPhoto() {
		return photo;
	}

	public void setPhoto(File photo) {
		this.photo = photo;
	}

	public String getPhotoFileName() {
		return photoFileName;
	}

	public void setPhotoFileName(String photoFileName) {
		this.photoFileName = photoFileName;
	}

	public Integer getTenancy() {
		return tenancy;
	}

	public void setTenancy(Integer tenancy) {
		this.tenancy = tenancy;
	}

	public Integer getTenancyType() {
		return tenancyType;
	}

	public void setTenancyType(Integer tenancyType) {
		this.tenancyType = tenancyType;
	}
	
	@Transient
	public BigDecimal getFixedFeeTotalAmount() {
		return fixedFeeTotalAmount;
	}

	public void setFixedFeeTotalAmount(BigDecimal fixedFeeTotalAmount) {
		this.fixedFeeTotalAmount = fixedFeeTotalAmount;
	}
	
	@Transient
	public FeeRecord getLastFeeRecord() {
		return lastFeeRecord;
	}

	public void setLastFeeRecord(FeeRecord lastFeeRecord) {
		this.lastFeeRecord = lastFeeRecord;
	}
}
